#include "TextBox.h"

using namespace std;

CTextBox::CTextBox()
{
	m_border_width_tb=7;
	m_border_width_lr=12;
	m_text_space=0;
	readyToOutput=false;
}

CTextBox::~CTextBox(void)
{
}

void CTextBox::SetText( const char* text )
{
	CAllegroWindow::SetText(text);
	if(readyToOutput)
	{
		BuildLines();
		RedrawBuffer();
	}
}

void CTextBox::SetRect( int x1, int y1, int x2, int y2 )
{
	CAllegroWindow::SetRect(x1,y1,x2,y2);



	BuildLines();
	RedrawBuffer();

	readyToOutput = true;
}

void CTextBox::Draw( BITMAP* sb )
{
	CAllegroWindow::Draw(sb);
	
}

void CTextBox::BuildLines()
{
	m_lines.clear();

	if(m_text==NULL)
		return;
	if(m_text[0]=='\0')
		return;
	if(m_font==NULL)
		return;

	int len = strlen(m_text);
	char lastSymbol = 0;
	string currWord="";
	string currLine="";
	int textSpace = (m_x2-m_x1)-2*m_border_width_lr;
	

	for(int i=0;i<len;i++)
	{
		char ch = m_text[i];
		if(ch==' ')
		{
			if(lastSymbol==' ')
			{
				
			}
			else
			{
				string testLine = currLine+currWord;
				int currLineLen = alfont_text_length(m_font,testLine.c_str());
				if(currLineLen>textSpace)
				{
					m_lines.push_back(currLine);
					currLine = currWord+" ";
				}
				else
				{
					currLine+=currWord+" ";
				}
				currWord="";
			}
		}
		else
		{
			currWord+=ch;		
		}
		lastSymbol = m_text[i];
	}
	currLine+=currWord;
	if(currLine!="")
	{
		m_lines.push_back(currLine);
	}
}

void CTextBox::RedrawBuffer()
{
	//rect(m_wb,0,0,m_wb->w-1,m_wb->h-1,makecol(127,127,127));
	CAllegroWindow::RedrawBuffer();
	if(m_lines.size()==0)
		return;

	int cx=m_border_width_lr;
	int cy=m_border_width_tb;
	int strH = alfont_get_font_height(m_font);
	for(vector<string>::iterator it = m_lines.begin();it != m_lines.end();++it)
	{
		alfont_textprintf_aa(m_wb,m_font,cx,cy,makecol(255,255,255),"%s",it->c_str());
		cy+=m_text_space+strH;
	}

}

void CTextBox::SetFont( ALFONT_FONT* font )
{
	CAllegroWindow::SetFont(font);
	if(readyToOutput)
	{
		BuildLines();
		RedrawBuffer();
	}
}